package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UsersApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.Announcement;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Contacts;
import com.tanhua.server.vo.MessageAnnouncement;
import com.tanhua.server.vo.MessageLike;
import com.tanhua.server.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class IMService {

    @Reference(version = "1.0.0")
    private UsersApi usersApi;

    @Reference(version ="1.0.0")
    private QuanZiApi quanZiApi;

    @Value("${tanhua.sso.url}")
    private String ssoUrl;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private  UserInfoService userInfoService;

    @Autowired
    private AnnouncementService announcementService;

    public Boolean contactsUser(Long userId) {
        //保存数据到mongoDB
        Users users = new Users();
        users.setUserId(UserThreadLocal.get().getId());
        users.setFriendId(userId);

        Users users2 = new Users();
        users2.setUserId(userId);
        users2.setFriendId(UserThreadLocal.get().getId());

        //2.将数据保存到mongoDB,因为mongoDB不会双向添加,所以需要建立两个
        this.usersApi.saveUsers(users);
        this.usersApi.saveUsers(users2);



        //2.好友关系注册到环信
        String url = ssoUrl + "/user/huanxin/contacts/"
                + users.getUserId() + "/" + users.getFriendId();

        ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(url, null, Void.class);
        if (responseEntity.getStatusCodeValue() == 200) {
            return true;
        }
        return false;
    }

    /**
     * 根据参数 获得联系人列表
     * @param page
     * @param pageSize
     * @param keyWord  昵称  模糊搜索
     * @return
     */
    public PageResult queryContacts(Integer page, Integer pageSize, Integer keyWord) {
        //1.从mongoDB获取数据,远程调用(全部查询)  不分页
        User user = UserThreadLocal.get();
        List<Users> users=this.usersApi.queryAllUsersList(user.getId());
        //2.判断
        if (users==null||users.size()<=0){
            return new PageResult(0,0,0,0, Collections.emptyList());
        }
        //3.分页+条件查询,查询msq
        // 1)获得 好友 ids
        List<Long> ids= new ArrayList();
        for (Users user1: users) {
            ids.add(user1.getFriendId());
        }
        // in 查询
        QueryWrapper query = new QueryWrapper();
        query.in("user_id",ids);
        IPage<UserInfo> pageMysql = this.userInfoService.queryUserInfoList(page, pageSize, query);
        List<UserInfo> userInofs = pageMysql.getRecords();
        //4 定义封装联系人VO 集合返回,整合 第一步和第三步的数据 返回一个VO  对象
        List<Contacts> contactsList = new ArrayList<>();
        for (UserInfo userInfo : userInofs) {
            Contacts contacts = new Contacts();
            contacts.setCity(StringUtils.substringBefore(userInfo.getCity(),"-"));
            contacts.setUserId(userInfo.getUserId().toString());
            contacts.setNickname(userInfo.getNickName());
            contacts.setGender(userInfo.getSex().name().toLowerCase());
            contacts.setAvatar(userInfo.getLogo());
            contacts.setAge(userInfo.getAge());
            contactsList.add(contacts);
        }
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(contactsList);
        return pageResult;
    }

    /**
     * 查询消息点赞
     * @param page
     * @param pageSize
     * @return
     */

    public PageResult queryMessageLikeList(Integer page, Integer pageSize) {
        /*User user = UserThreadLocal.get();
       //分页查询
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentListByUser(user.getId(), 1, page, pageSize);
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);
        List<Comment> records = pageInfo.getRecords();
        List<Long> userIds = new ArrayList<>();
        for (Comment comment : records) {
            userIds.add(comment.getUserId());
        }

        //查询用户
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",userIds);
       //传递查询用户
        List<UserInfo> userInfoList = this.userInfoService.queryList(queryWrapper);
        List<MessageLike> messageLikeList = new ArrayList<>();
        //用户信息
        for (Comment record : records) {
            for (UserInfo userInfo : userInfoList) {
               if (userInfo.getUserId().longValue()==record.getUserId().longValue()){
                   MessageLike messageLike = new MessageLike();
                   messageLike.setId(record.getId().toHexString());
                   messageLike.setAvatar(userInfo.getLogo());
                   messageLike.setNickname(userInfo.getNickName());
                   //时间日期格式化
                   messageLike.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));
                   messageLikeList.add(messageLike);
                   break;
               }
            }
        }
        pageResult.setItems(messageLikeList);
        return pageResult;*/
       return this.messageCommentList(1, page, pageSize);

    }

    /**
     * 查询评论列表
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageCommentList(Integer page, Integer pageSize) {
        return this.messageCommentList(2, page, pageSize);
    }

    public PageResult queryMessageLoveList(Integer page, Integer pageSize) {
        return this.messageCommentList(3, page, pageSize);

    }

    /**
     * 将上面的重复代码抽取出来  然后调用
     * @param type
     * @param page
     * @param pageSize
     * @return
     */
    private PageResult messageCommentList(Integer type, Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentListByUser(user.getId(), type, page, pageSize);
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);

        List<Comment> records = pageInfo.getRecords();

        List<Long> userIds = new ArrayList<>();
        for (Comment comment : records) {
            userIds.add(comment.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryList(queryWrapper);
        List<MessageLike> messageLikeList = new ArrayList<>();
        for (Comment record : records) {
            for (UserInfo userInfo : userInfoList) {
                if (userInfo.getUserId().longValue() == record.getUserId().longValue()) {

                    MessageLike messageLike = new MessageLike();
                    messageLike.setId(record.getId().toHexString());
                    messageLike.setAvatar(userInfo.getLogo());
                    messageLike.setNickname(userInfo.getNickName());
                    messageLike.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));

                    messageLikeList.add(messageLike);
                    break;
                }
            }
        }
        pageResult.setItems(messageLikeList);
        return pageResult;
    }

    /**
     * 查询公告列表
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        IPage<Announcement> announcementIPage = this.announcementService.queryList(page, pageSize);

        List<MessageAnnouncement> messageAnnouncementList = new ArrayList<>();

        for (Announcement record : announcementIPage.getRecords()) {

            MessageAnnouncement messageAnnouncement = new MessageAnnouncement();
            messageAnnouncement.setId(record.getId().toString());
            messageAnnouncement.setTitle(record.getTitle());
            messageAnnouncement.setDescription(record.getDescription());
            //时间需要格式化
            messageAnnouncement.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));

            messageAnnouncementList.add(messageAnnouncement);
        }
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(messageAnnouncementList);
        return pageResult;
    }
}
